package com.gitee.fsmxm.thinking.in.concurrent.basic;

import java.util.concurrent.locks.StampedLock;

/**
 * StampedLock:
 * <p>悲观读锁：和悲观写锁互斥；允许多个线程持有读锁；
 * <p>悲观写锁：和悲观读锁/悲观写锁互斥；
 * <p>乐观读锁：乐观读时可允许获取悲观写锁。
 */
public class _08_StampedLock_Point {
    public static class Point {
        private double x, y;
        private final StampedLock sl = new StampedLock();

        // 坐标移动，独占锁定模式（写锁模式）
        void move(double deltaX, double deltaY) {
            final StampedLock sl = this.sl;
            long stamp = sl.writeLock();
            try {
                x += deltaX;
                y += deltaY;
            } finally {
                sl.unlockWrite(stamp);
            }
        }

        // 计算坐标和原点的距离，乐观读锁模式
        double distanceFromOrigin() {
            final StampedLock sl = this.sl;
            long stamp = sl.tryOptimisticRead(); // 乐观读锁
            double currentX = x, currentY = y;
            if (!sl.validate(stamp)) { // 检测是否被独占获取锁
                stamp = sl.readLock(); // 加 “悲观读锁”，后续操作不会有写入操作
                try {
                    currentX = x;
                    currentY = y;
                } finally {
                    sl.unlockRead(stamp);
                }
            }
            return Math.sqrt(currentX * currentX + currentY * currentY);
        }

        // 移动坐标如果在原点，锁的升级
        void moveIfAtOrigin(double newX, double newY) {
            final StampedLock sl = this.sl;
            long stamp = sl.readLock(); // 可以使用乐观读锁模式代替
            try {
                while (x == 0.0 && y == 0.0) {
                    long ws = sl.tryConvertToWriteLock(stamp); // 升级为悲观写锁
                    if (ws != 0L) { // 升级写锁成功
                        stamp = ws;
                        x = newX;
                        y = newY;
                        break;
                    } else { // 升级写锁失败
                        sl.unlockRead(stamp);
                        stamp = sl.writeLock();
                    }
                }
            } finally {
                sl.unlock(stamp);
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        final Point point = new Point();

        Thread t1 = new Thread(() -> {
            point.move(2, 3);
            System.out.println("t1: " + point.distanceFromOrigin());
        }, "t1");
        Thread t2 = new Thread(() -> {
            point.moveIfAtOrigin(3, 4);
            System.out.println("t1: " + point.distanceFromOrigin());
        }, "t2");
        Thread t3 = new Thread(() -> {
            point.move(1, 2);
            point.move(0, 0);
        }, "t3");


        t1.start();
        t2.start();
        t3.start();

        t1.join();
        t2.join();
        t3.join();
    }
}
